package org.sraosha.base.thread;

import org.sraosha.base.mapper.UaClientMapper;
import org.sraosha.framework.constants.RedisStorage;
import org.sraosha.framework.manager.RedisManager;
import org.sraosha.base.model.UaClient;
import org.sraosha.base.pojo.constants.RedisKey;
import org.sraosha.base.value.RedisParamConfig;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;

/**
 * 将ua_client表中的数据保存到redis中
 */
@Slf4j
public class SaveUaClientInRedisThread implements Callable {

    private RedisManager redisManager;

    private RedisParamConfig redisParamConfig;

    private UaClientMapper uaClientMapper;

    public SaveUaClientInRedisThread(RedisManager redisManager, RedisParamConfig redisParamConfig, UaClientMapper uaClientMapper) {
        this.redisManager = redisManager;
        this.redisParamConfig = redisParamConfig;
        this.uaClientMapper = uaClientMapper;
    }

    @Override
    public Object call() throws Exception {
        // 创建redis分布式锁
        StringBuffer redisLockKey = new StringBuffer().append(RedisKey.SRAOSHA).append(RedisStorage.COLON).append(RedisKey.SRAOSHA)
                .append(RedisStorage.COLON).append(RedisStorage.LOCK_KEY_PREFIX)
                .append(RedisKey.SRAOSHA);
        StringBuffer redisLockValue = new StringBuffer().append(UUID.randomUUID()).append("-").append(Thread.currentThread().getId());
        // 获取锁对象
        boolean isLock = redisManager.tryLock(redisLockKey.toString(), redisLockValue.toString(), redisParamConfig.getLockTimeout());

        // 加锁失败
        if (!isLock) {
            log.warn("redis的分布式锁创建失败，因此分布式锁已经存在，key为【{}】，value为【{}】", redisLockKey, redisLockValue);
            return null;
        }
        log.info("redis的分布式锁创建成功，key为【{}】，value为【{}】", redisLockKey, redisLockValue);

        try {
            // 查询auth_client表的全部记录
            List<UaClient> authClientList = uaClientMapper.selectList(null);
            if (null != authClientList && authClientList.size() > 0) {
                // 将auth_client信息存储到redis
                StringBuffer key = new StringBuffer().append(RedisKey.SRAOSHA).append(RedisStorage.COLON).append(RedisKey.SRAOSHA)
                        .append(RedisStorage.COLON).append(RedisKey.SRAOSHA);
                redisManager.set(key.toString(), JSON.toJSONString(authClientList));
            }
            Thread.sleep(redisParamConfig.getLockWaitingTime());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            redisManager.unlock(redisLockKey.toString(), redisLockValue.toString());
            log.info("redis的分布式锁释放成功，key为【{}】，value为【{}】", redisLockKey, redisLockValue);
        }

        return null;
    }
}
